//
//  XHContentView.m
//  XHNewsFramework
//
//  Created by 曾 宪华 on 14-1-24.
//  Copyright (c) 2014年 曾宪华 开发团队(http://iyilunba.com ) 本人QQ:543413507 本人QQ群（142557668）. All rights reserved.
//

#import "XHContentView.h"

#define kXHTransitionDuration	0.4

@implementation XHContentView

- (void)setTableViewContentInsetTop:(CGFloat)tableViewContentInsetTop {
    _tableViewContentInsetTop = tableViewContentInsetTop;
    UIEdgeInsets contentInset = _tableView.contentInset;
    contentInset.top = _tableViewContentInsetTop;
    _tableView.contentInset = contentInset;
    _tableView.scrollIndicatorInsets = contentInset;
}

#pragma mark init

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
		[self setBackgroundColor:[UIColor whiteColor]];
		self.transitionDuration = kXHTransitionDuration;
		_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,frame.size.width,frame.size.height)];
		[self addSubview:_tableView];
		[_tableView setDelegate:self];
		[_tableView setDataSource:self];
		[_tableView setScrollsToTop:NO];
    }
    return self;
}

- (id)initWithIdentifier:(NSString *)identifier {
    if (self = [super init]) {
		_identifier = identifier;
	}
	return self;
}

- (void)setFrame:(CGRect)frame {
	[super setFrame:frame];
	
	CGRect tableViewFrame = [self.tableView frame];
	tableViewFrame.size.width = self.frame.size.width;
	tableViewFrame.size.height = self.frame.size.height;
	[self.tableView setFrame:tableViewFrame];
}

#pragma mark reset

- (void)reset {
    
}

#pragma mark view state

- (void)pageWillAppear {
    if (self.restored) {
        [self.tableView reloadData];
        [self restoreTableviewOffset];
    }
}

- (void)pageDidAppear {
    [_tableView setScrollsToTop:YES];
}

- (void)pageWillDisappear {
    [_tableView setScrollsToTop:NO];
    if (self.restored)
        [self saveTableviewOffset];
}

#pragma mark animation

- (void)show:(BOOL)show {
    if (show) {
		self.transform = CGAffineTransformScale([self transformForOrientation], 0.001, 0.001);
	} else {
		[self removeTableviewOffset];
		self.transform = CGAffineTransformScale([self transformForOrientation], 1, 1);
	}
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationDuration:0.2];
	[UIView setAnimationDelegate:self];
	if (show) {
		[UIView setAnimationDidStopSelector:@selector(bounce1AnimationStopped)];
		self.transform = CGAffineTransformScale([self transformForOrientation], 1.05, 1.05);
	} else {
		[UIView setAnimationDidStopSelector:@selector(bounce4AnimationStopped)];
		self.transform = CGAffineTransformScale([self transformForOrientation], 1.05, 1.05);
	}
	[UIView commitAnimations];
}

- (void)bounce1AnimationStopped {
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:self.transitionDuration/3];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(bounce2AnimationStopped)];
	self.transform = CGAffineTransformScale([self transformForOrientation], 0.9, 0.9);
	[UIView commitAnimations];
}

- (void)bounce2AnimationStopped {
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:self.transitionDuration/4];
	self.transform = [self transformForOrientation];
	[UIView commitAnimations];
}

- (void)bounce3AnimationStopped {
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:self.transitionDuration/4];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(bounce4AnimationStopped)];
	self.transform = CGAffineTransformScale([self transformForOrientation], 1.1, 1.1);
	[UIView commitAnimations];
}

- (void)bounce4AnimationStopped {
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:self.transitionDuration/1.5];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(completedHidingAnimation)];
	self.transform = CGAffineTransformScale([self transformForOrientation], 0.001, 0.001);
	[UIView commitAnimations];
}

- (void)completedHidingAnimation {
}

- (CGAffineTransform)transformForOrientation {
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
	if (orientation == UIInterfaceOrientationLandscapeLeft) {
		return CGAffineTransformMakeRotation(M_PI*1.5);
	} else if (orientation == UIInterfaceOrientationLandscapeRight) {
		return CGAffineTransformMakeRotation(M_PI/2);
	} else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
		return CGAffineTransformMakeRotation(-M_PI);
	} else {
		return CGAffineTransformIdentity;
	}
}

- (void)showContentView:(BOOL)show animated:(BOOL)animated {
    if (animated) {
		[self show:show];
	} else {
		[self setHidden:!show];
		if (show) {
			self.transform = CGAffineTransformScale([self transformForOrientation], 1, 1);
		} else {
			
		}
	}
}

- (void)shouldWiggle:(BOOL)wiggle {
    if (wiggle) {
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.1];
		[UIView setAnimationRepeatAutoreverses:YES];
		[UIView setAnimationRepeatCount:10000];
		[self setTransform:CGAffineTransformMakeRotation(1*M_PI/180.0)];
		[self setTransform:CGAffineTransformMakeRotation(-1*M_PI/180.0)];
		[UIView commitAnimations];
	} else {
		[self setTransform:CGAffineTransformMakeRotation(0)];
		[self.layer removeAllAnimations];
	}
}

#pragma mark offset save/restore

#define kXHTableViewOffset @"XHTableViewOffset"

- (void)saveTableviewOffset {
    CGPoint contentOffset = [self.tableView contentOffset];
	float y = contentOffset.y;
	
	NSMutableArray *offsetArray = [[[NSUserDefaults standardUserDefaults] objectForKey:kXHTableViewOffset] mutableCopy];
	if (!offsetArray) {
		offsetArray = [NSMutableArray array];
	}
	
	if ([offsetArray count] < self.pageNumber + 1) {
		[offsetArray addObject:@(y)];
	} else {
		[offsetArray replaceObjectAtIndex:self.pageNumber withObject:[NSNumber numberWithInt:y]];
	}
	
	[[NSUserDefaults standardUserDefaults] setObject:offsetArray forKey:kXHTableViewOffset];
}

- (void)restoreTableviewOffset {
    NSMutableArray *offsetArray = [[NSUserDefaults standardUserDefaults] objectForKey:kXHTableViewOffset];
	if (offsetArray) {
		if ([offsetArray count]>self.pageNumber) {
			float y = [[offsetArray objectAtIndex:self.pageNumber] floatValue];
			CGPoint contentOffset = CGPointMake(0, y);
			[self.tableView setContentOffset:contentOffset animated:NO];
		}
	}
}

- (void)removeTableviewOffset {
    NSMutableArray *offsetArray = [[[NSUserDefaults standardUserDefaults] objectForKey:kXHTableViewOffset] mutableCopy];
	if (offsetArray) {
		if ([offsetArray count]>self.pageNumber) {
			
			[offsetArray removeObjectAtIndex:self.pageNumber];
			[[NSUserDefaults standardUserDefaults] setObject:offsetArray forKey:kXHTableViewOffset];
		}
	}
}

#pragma mark add and remove panels

- (void)addContentViewWithAnimation:(BOOL)animate {
    if (animate) {
        [self showContentView:YES animated:YES];
	}
}

- (void)removeContentViewWithAnimation:(BOOL)animate {
    if (animate) {
		[self showContentView:NO animated:YES];
		[self performSelector:@selector(showNextContentView) withObject:nil afterDelay:0.9];
	}
}

#pragma mark page controll

- (void)showNextContentView {
    CGAffineTransform scaleTransform = CGAffineTransformScale([self transformForOrientation], 1, 1);
	[self setTransform:scaleTransform];
	CGAffineTransform translateTransform = CGAffineTransformTranslate([self transformForOrientation], self.frame.size.width, 0);
	[self setTransform:translateTransform];
    
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationDuration:0.2];
    translateTransform = CGAffineTransformMakeTranslation(0, 0);
	[self setTransform:translateTransform];
	[UIView commitAnimations];
}

- (void)showPreviousContentView {
    CGAffineTransform scaleTransform = CGAffineTransformScale([self transformForOrientation], 1, 1);
	[self setTransform:scaleTransform];
	CGAffineTransform translateTransform = CGAffineTransformTranslate([self transformForOrientation], -1*self.frame.size.width, 0);
	[self setTransform:translateTransform];
	
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationDuration:0.2];
	
	translateTransform = CGAffineTransformMakeTranslation(0, 0);
	[self setTransform:translateTransform];
	
	[UIView commitAnimations];
}

#pragma mark table

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	if ([self.delegate respondsToSelector:@selector(contentView:heightForRowAtIndexPath:)]) {
		return [self.delegate contentView:self heightForRowAtIndexPath:[XHPageIndexPath panelIndexPathForPage:self.pageNumber indexPath:indexPath]];
	}
	else return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if ([self.delegate respondsToSelector:@selector(contentView:didSelectRowAtIndexPath:)]) {
		return [self.delegate contentView:self didSelectRowAtIndexPath:[XHPageIndexPath panelIndexPathForPage:self.pageNumber indexPath:indexPath]];
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	if ([self.delegate respondsToSelector:@selector(contentView:cellForRowAtIndexPath:)]) {
		return [self.delegate contentView:self cellForRowAtIndexPath:[XHPageIndexPath panelIndexPathForPage:self.pageNumber indexPath:indexPath]];
	}
	return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if ([self.delegate respondsToSelector:@selector(contentView:numberOfRowsInPage:section:)]) {
		return [self.delegate contentView:self numberOfRowsInPage:self.pageNumber section:section];
	}
	return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	if ([self.delegate respondsToSelector:@selector(contentView:numberOfSectionsInPage:)]) {
		return [self.delegate contentView:self numberOfSectionsInPage:self.pageNumber];
	}
	return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if ([self.delegate respondsToSelector:@selector(contentView:titleForHeaderInPage:section:)]) {
		return [self.delegate contentView:self titleForHeaderInPage:self.pageNumber section:section];
	}
	return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if ([self.delegate respondsToSelector:@selector(contentView:viewForHeaderInPage:section:)]) {
        return [self.delegate contentView:self viewForHeaderInPage:self.pageNumber section:section];
    }
    return nil;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([self.delegate respondsToSelector:@selector(contentView:didScroll:)]) {
        return [self.delegate contentView:self didScroll:scrollView];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self.delegate respondsToSelector:@selector(contentView:heightForHeaderInSection:)]) {
        return [self.delegate contentView:self heightForHeaderInSection:section];
    } else {
        return 44;
    }
}

@end
